package cn.com.libertymutual.core.database.druid.aop;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.PriorityOrdered;
import org.springframework.stereotype.Component;

import cn.com.libertymutual.core.database.druid.DataSourceContextHolder;
import cn.com.libertymutual.core.database.druid.DataSourceType;

/** 
 * 在service层决定数据源 
 *  
 * 要想在事务AOP之前执行，就必须实现Ordered接口或者PriorityOrdered子接口,order的值越小，越先执行 
 * 如果一旦开始切换到写库，则之后的读都会走写库 
 *  
 * @author
 * 
 */
@Aspect
@Component
@EnableAspectJAutoProxy(exposeProxy = true, proxyTargetClass = true)
public class DataSourceAopInService implements PriorityOrdered {

	// private Logger log = LoggerFactory.getLogger(getClass());

	@Before("execution(* cn.com.libertymutual.*.service..*.find*(..)) or execution(* cn.com.libertymutual.*.service..*.query*(..)) "
			+ "or execution(* cn.com.libertymutual.*.service..*.get*(..))")
	public void setReadDataSourceType() {
		// 如果已经开启写事务了，那之后的所有读都从写库读
		if (!DataSourceType.write.getType().equals(DataSourceContextHolder.getJdbcType())) {
			DataSourceContextHolder.read();
		}
		// log.info("DataSourceAopInService切换到：Read");
	}

	@Before("execution(* cn.com.libertymutual.*.service..*.insert*(..)) or execution(* cn.com.libertymutual.*.service..*.save*(..)) "
			+ "or execution(* cn.com.libertymutual.*.service..*.add*(..)) or execution(* cn.com.libertymutual.*.service..*.create*(..)) "
			+ "or execution(* cn.com.libertymutual.*.service..*.update*(..)) or execution(* cn.com.libertymutual.*.service..*.set*(..)) "
			+ "or execution(* cn.com.libertymutual.*.service..*.delete*(..)) or execution(* cn.com.libertymutual.*.service..*.remove*(..))")
	public void setWriteDataSourceType() {
		DataSourceContextHolder.write();
		// log.info("DataSourceAopInService切换到：write");
	}

	@Override
	public int getOrder() {
		/** 
		 * 值越小，越优先执行 
		 * 要优于事务的执行 
		 * 在启动类中加上了@EnableTransactionManagement(order = 10)  
		 */
		return 1;
	}

}